package controllers

import (
	"fmt"
	"gindemo02/models"
	"net/http"

	"github.com/gin-gonic/gin"
)

type ContactController struct {
	BaseController
}

func (con ContactController) Add(c *gin.Context) {

	var currentData struct {
		UserID int64 `json:"userid" binding:"required"`
		DstID  int64 `json:"dstid" binding:"required"`
	}

	// 绑定请求数据到currentData变量
	if err := c.ShouldBindJSON(&currentData); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"code": 40101, "msg": "传入的变量数据错误", "error": err.Error()})
		return
	}

	// 获取当前用户ID
	currentUserID := currentData.UserID

	// 获取目标用户ID
	dstUserID := currentData.DstID

	fmt.Println("currentUserID", currentData)
	fmt.Println("dstUserID", dstUserID)

	// 开启事务
	tx := models.DB.Begin()

	// 1. 不能加自己为好友
	if currentUserID == dstUserID {
		tx.Rollback()
		c.JSON(http.StatusBadRequest, gin.H{
			"error": "不能加自己为好友",
		})
		return
	}

	// 2. 判断是否已经是好友
	var existingContact models.Contact
	result := tx.Where("ownerid = ? AND dstobj = ? AND cate = ?", currentUserID, dstUserID, models.CONCAT_CATE_USER).First(&existingContact)
	if result.Error == nil && result.RowsAffected > 0 {
		tx.Rollback()
		c.JSON(http.StatusBadRequest, gin.H{
			"error": "已经是好友",
		})
		return
	}

	// 3. 写入数据到Contact
	newContact1 := models.Contact{
		Ownerid: currentUserID,
		Dstobj:  dstUserID,
		Cate:    models.CONCAT_CATE_USER,
		Status:  0,
	}

	if err := tx.Create(&newContact1).Error; err != nil {
		tx.Rollback()
		c.JSON(http.StatusInternalServerError, gin.H{
			"error": "添加好友失败1",
		})
		return
	}

	newContact2 := models.Contact{
		Ownerid: dstUserID,
		Dstobj:  currentUserID,
		Cate:    models.CONCAT_CATE_USER,
		Status:  0,
	}

	if err := tx.Create(&newContact2).Error; err != nil {
		tx.Rollback()
		c.JSON(http.StatusInternalServerError, gin.H{
			"error": "添加好友失败2",
		})
		return
	}

	// 提交事务
	if err := tx.Commit().Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"error": "添加好友失败3",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"message": "成功添加好友",
	})
}

// 获取好友列表
func (con ContactController) List(c *gin.Context) {
	userID := c.Query("userID")

	var contacts []models.Contact
	if err := models.DB.Where("ownerid = ?", userID).Find(&contacts).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"error": err.Error(),
		})
		return
	}

	fmt.Println("contacts", contacts)

	var friendIDs []int64
	for _, contact := range contacts {
		friendIDs = append(friendIDs, contact.Dstobj)
	}

	var friends []models.Account
	if err := models.DB.Where("id IN ?", friendIDs).Find(&friends).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"error": err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"friends": friends,
	})
}
